/**
 * 2013-5-15 上午11:24:33 Created By niexiaoqiang
 */

package com.xiaoqiang.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

import org.apache.log4j.Logger;

import com.xiaoqiang.util.MsgRecivedEvent;
import com.xiaoqiang.util.MsgRecivedListener;

/**
 * TODO Add Class Description
 */
public class RequestProcessor implements Runnable {
	private MtwServer server;
	private Socket socket;
	private static Logger log = Logger.getLogger(MtwServer.class);
	private Collection<MsgRecivedListener> listeners;

	public void addMsgRecivedListener(MsgRecivedListener listener) {
		if (listeners == null) {
			listeners = new HashSet<MsgRecivedListener>();
		}
		listeners.add(listener);
		log.debug("add listener:" + listener.getClass());
	}

	public void removeMsgRecivedListener(MsgRecivedListener listener) {
		if (listeners == null)
			return;
		listeners.remove(listener);
		log.debug("remove listener:" + listener.getClass());
	}

	private void notifyListeners(MsgRecivedEvent event) {
		Iterator<MsgRecivedListener> iter = listeners.iterator();
		while (iter.hasNext()) {
			MsgRecivedListener listener = (MsgRecivedListener) iter.next();
			listener.msgRecivedEvent(event);
			log.debug("notify listener:" + listener.getClass());
		}
	}

	public RequestProcessor(MtwServer server, Socket socket, InetAddress ip) {
		this.server = server;
		this.socket = socket;
		log.debug("Thread for " + ip + "init");
	}

	@Override
	public void run() {
		if (this.server.isRunning() && this.socket != null && this.socket.isConnected()) {
			InetAddress ip = this.socket.getInetAddress();
			BufferedReader br = null;
			// PrintWriter pw = null;
			String line = null;
			try {
				InputStream is = this.socket.getInputStream();
				br = new BufferedReader(new InputStreamReader(is));
				// pw = new PrintWriter(this.socket.getOutputStream(), true);
				while ((line = br.readLine()) != null) {
					log.info(ip + " recived msg:" + line);
					if (listeners == null) {
						log.error("there is no listenr,application continue");
						continue;
					}
					MsgRecivedEvent event = new MsgRecivedEvent(line);
					log.debug(ip + " notify all Listeners :" + line);
					/*************/
					// notifyListeners(event);
					/**********/
					// pw.println("服务器自动回复 ^_^ ");
					// pw.flush();
				}
			}
			catch (SocketException e) {
				log.error("client " + ip + " if outline");
			}
			catch (IOException e) {
				log.error(e);
			}
			finally {
				try {
					if (br != null) {
						br.close();
						br = null;
					}
				}
				catch (IOException e) {
				}
			}
		}
	}
}
